<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>恐龙跑酷</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f7f7f7;
            font-family: Arial, sans-serif;
        }
        
        #game-container {
            position: relative;
            width: 800px;
            height: 300px;
            overflow: hidden;
            border: 1px solid #ddd;
            background-color: white;
        }
        
        canvas {
            position: absolute;
            top: 0;
            left: 0;
        }
        
        #score-container {
            position: absolute;
            top: 10px;
            left: 20px;
            font-size: 20px;
            color: #535353;
            z-index: 10;
        }
        
        #high-score {
            font-size: 16px;
            color: #767676;
        }
        
        #game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 24px;
            color: #535353;
            display: none;
            text-align: center;
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        
        #game-over button {
            padding: 8px 16px;
            margin-top: 10px;
            background-color: #535353;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        #instructions {
            position: absolute;
            bottom: 10px;
            left: 10px;
            font-size: 12px;
            color: #767676;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <canvas id="game-canvas"></canvas>
        <div id="score-container">
            <div id="score">0</div>
            <div id="high-score">HI: 0</div>
        </div>
        <div id="game-over">
            游戏结束
            <br>
            <button id="restart-button">重新开始</button>
        </div>
        <div id="instructions">
            空格键：跳跃 | 下箭头：下蹲
        </div>
    </div>

    <script>
        // 游戏基本设置
        const gameWidth = 800;
        const gameHeight = 300;
        const groundHeight = 40;
        
        // 恐龙尺寸和位置
        const dinoWidth = 44;
        const dinoHeight = 48;
        const dinoDuckHeight = 30;
        const dinoX = 50;
        
        // 障碍物设置
        const minObstacleInterval = 1000; // 最短生成间隔(ms)
        const maxObstacleInterval = 3000; // 最长生成间隔(ms)
        
        // 游戏速度和分数
        let gameSpeed = 6;
        let score = 0;
        let highScore = 0; // 仅使用内存变量，不使用localStorage
        let gameOver = false;
        let isDucking = false;
        const acceleration = 0.001; // 游戏加速度
        
        // 初始化Matter.js引擎
        const Engine = Matter.Engine;
        const Render = Matter.Render;
        const World = Matter.World;
        const Bodies = Matter.Bodies;
        const Body = Matter.Body;
        const Events = Matter.Events;
        const Runner = Matter.Runner;
        
        const engine = Engine.create({
            gravity: { x: 0, y: 1.5 }
        });
        const world = engine.world;
        
        // 创建渲染器
        const render = Render.create({
            element: document.getElementById('game-container'),
            engine: engine,
            canvas: document.getElementById('game-canvas'),
            options: {
                width: gameWidth,
                height: gameHeight,
                wireframes: false,
                background: 'white'
            }
        });
        
        // 创建地面
        const ground = Bodies.rectangle(
            gameWidth / 2,
            gameHeight - groundHeight / 2,
            gameWidth,
            groundHeight,
            {
                isStatic: true,
                render: {
                    fillStyle: '#cccccc'
                }
            }
        );
        
        // 创建恐龙
        let dino = Bodies.rectangle(
            dinoX,
            gameHeight - groundHeight - dinoHeight / 2,
            dinoWidth,
            dinoHeight,
            {
                label: 'dino',
                friction: 1,
                restitution: 0,
                render: {
                    sprite: {
                        texture: createDinoImage(false),
                        xScale: 1,
                        yScale: 1
                    }
                }
            }
        );
        
        // 添加到世界
        World.add(world, [ground, dino]);
        
        // 开始渲染
        Render.run(render);
        
        // 使用Runner代替Engine.run
        const runner = Runner.create();
        Runner.run(runner, engine);
        
        // 碰撞检测
        Events.on(engine, 'collisionStart', function(event) {
            const pairs = event.pairs;
            
            for (let i = 0; i < pairs.length; i++) {
                const pair = pairs[i];
                
                if (
                    (pair.bodyA.label === 'dino' && pair.bodyB.label === 'obstacle') ||
                    (pair.bodyA.label === 'obstacle' && pair.bodyB.label === 'dino')
                ) {
                    endGame();
                }
            }
        });
        
        // 障碍物管理
        const obstacles = [];
        let lastObstacleTime = 0;
        let nextObstacleTime = getRandomInterval();
        
        // 主游戏循环
        function gameLoop(timestamp) {
            if (gameOver) return;
            
            // 添加障碍物
            if (timestamp - lastObstacleTime > nextObstacleTime) {
                addObstacle();
                lastObstacleTime = timestamp;
                nextObstacleTime = getRandomInterval();
            }
            
            // 更新和移除障碍物
            updateObstacles();
            
            // 更新分数
            score++;
            const displayScore = Math.floor(score / 10);
            document.getElementById('score').innerText = displayScore;
            
            // 更新最高分
            if (displayScore > highScore) {
                highScore = displayScore;
                document.getElementById('high-score').innerText = 'HI: ' + highScore;
            }
            
            // 增加游戏速度
            gameSpeed += acceleration;
            
            requestAnimationFrame(gameLoop);
        }
        
        // 跳跃机制
        let canJump = true;
        
        function jump() {
            if (canJump && !gameOver) {
                const dinoPos = dino.position;
                const groundLevel = gameHeight - groundHeight - (isDucking ? dinoDuckHeight / 2 : dinoHeight / 2);
                
                // 只有当恐龙在地面附近时才能跳跃
                if (Math.abs(dinoPos.y - groundLevel) < 2) {
                    // 如果正在下蹲，先恢复正常姿态
                    if (isDucking) {
                        standUp();
                    }
                    
                    Body.setVelocity(dino, { x: 0, y: -13 });
                    canJump = false;
                    
                    // 跳跃冷却，防止连续跳跃
                    setTimeout(() => {
                        canJump = true;
                    }, 700);
                }
            }
        }
        
        // 下蹲机制
        function duck() {
            if (!isDucking && !gameOver) {
                isDucking = true;
                
                // 保存当前位置
                const position = { ...dino.position };
                
                // 从世界中移除当前恐龙
                World.remove(world, dino);
                
                // 创建下蹲状态的恐龙
                dino = Bodies.rectangle(
                    position.x,
                    position.y + (dinoHeight - dinoDuckHeight) / 2, // 调整Y位置使底部对齐
                    dinoWidth,
                    dinoDuckHeight,
                    {
                        label: 'dino',
                        friction: 1,
                        restitution: 0,
                        render: {
                            sprite: {
                                texture: createDinoImage(true),
                                xScale: 1,
                                yScale: 1
                            }
                        }
                    }
                );
                
                // 添加回世界
                World.add(world, dino);
            }
        }
        
        // 站立起来
        function standUp() {
            if (isDucking) {
                isDucking = false;
                
                // 保存当前位置
                const position = { ...dino.position };
                
                // 从世界中移除当前恐龙
                World.remove(world, dino);
                
                // 创建站立状态的恐龙
                dino = Bodies.rectangle(
                    position.x,
                    position.y - (dinoHeight - dinoDuckHeight) / 2, // 调整Y位置使底部对齐
                    dinoWidth,
                    dinoHeight,
                    {
                        label: 'dino',
                        friction: 1,
                        restitution: 0,
                        render: {
                            sprite: {
                                texture: createDinoImage(false),
                                xScale: 1,
                                yScale: 1
                            }
                        }
                    }
                );
                
                // 添加回世界
                World.add(world, dino);
            }
        }
        
        // 添加障碍物函数
        function addObstacle() {
            const obstacleTypes = ['cactus', 'cactusGroup', 'bat'];
            const type = obstacleTypes[Math.floor(Math.random() * obstacleTypes.length)];
            
            let obstacleWidth, obstacleHeight, textureSrc, yPosition;
            
            switch (type) {
                case 'cactus':
                    obstacleWidth = 20;
                    obstacleHeight = 50;
                    textureSrc = createCactusImage();
                    yPosition = gameHeight - groundHeight - obstacleHeight / 2;
                    break;
                case 'cactusGroup':
                    obstacleWidth = 50;
                    obstacleHeight = 35;
                    textureSrc = createCactusGroupImage();
                    yPosition = gameHeight - groundHeight - obstacleHeight / 2;
                    break;
                case 'bat':
                    obstacleWidth = 40;
                    obstacleHeight = 25;
                    textureSrc = createBatImage();
                    // 蝙蝠高度随机，确保需要跳或蹲
                    const batHeight = Math.random() > 0.5 ? 
                        // 高飞的蝙蝠，需要下蹲
                        gameHeight - groundHeight - dinoHeight - 20 :
                        // 低飞的蝙蝠，可以跳过
                        gameHeight - groundHeight - dinoDuckHeight / 2;
                    yPosition = batHeight;
                    break;
            }
            
            const obstacle = Bodies.rectangle(
                gameWidth + obstacleWidth,
                yPosition,
                obstacleWidth,
                obstacleHeight,
                {
                    label: 'obstacle',
                    isStatic: true,
                    render: {
                        sprite: {
                            texture: textureSrc,
                            xScale: 1,
                            yScale: 1
                        }
                    }
                }
            );
            
            World.add(world, obstacle);
            obstacles.push(obstacle);
        }
        
        // 更新障碍物位置
        function updateObstacles() {
            for (let i = obstacles.length - 1; i >= 0; i--) {
                const obstacle = obstacles[i];
                
                // 移动障碍物
                Body.translate(obstacle, { x: -gameSpeed, y: 0 });
                
                // 如果障碍物超出屏幕，从世界和数组中移除
                if (obstacle.position.x < -50) {
                    World.remove(world, obstacle);
                    obstacles.splice(i, 1);
                }
            }
        }
        
        // 获取随机障碍物间隔
        function getRandomInterval() {
            return Math.random() * (maxObstacleInterval - minObstacleInterval) + minObstacleInterval;
        }
        
        // 游戏结束函数
        function endGame() {
            // 添加死亡动画
            let flashCount = 0;
            let rotationAngle = 0;
            const maxFlash = 6;
            const deathAnimation = setInterval(() => {
                // 闪烁效果
                if (flashCount % 2 === 0) {
                    // 变红色
                    dino.render.sprite.texture = createDeadDinoImage();
                } else {
                    // 恢复原色
                    dino.render.sprite.texture = createDinoImage(isDucking);
                }
                
                // 旋转效果
                rotationAngle += Math.PI / 12;
                Body.setAngle(dino, rotationAngle);
                
                flashCount++;
                
                // 动画结束
                if (flashCount >= maxFlash) {
                    clearInterval(deathAnimation);
                    // 显示游戏结束界面
                    document.getElementById('game-over').style.display = 'block';
                }
            }, 150);
            
            gameOver = true;
        }
        
        // 重启游戏函数
        function restartGame() {
            // 清理障碍物
            for (const obstacle of obstacles) {
                World.remove(world, obstacle);
            }
            obstacles.length = 0;
            
            // 如果是下蹲状态，恢复正常姿态
            if (isDucking) {
                standUp();
            }
            
            // 重置恐龙位置
            Body.setPosition(dino, {
                x: dinoX,
                y: gameHeight - groundHeight - dinoHeight / 2
            });
            Body.setVelocity(dino, { x: 0, y: 0 });
            
            // 重置游戏参数
            gameSpeed = 6;
            score = 0;
            gameOver = false;
            isDucking = false;
            lastObstacleTime = 0;
            document.getElementById('score').innerText = '0';
            document.getElementById('game-over').style.display = 'none';
            
            // 重新开始游戏循环
            requestAnimationFrame(gameLoop);
        }
        
        // 创建恐龙图像
        function createDinoImage(ducking) {
            const canvas = document.createElement('canvas');
            canvas.width = dinoWidth;
            canvas.height = ducking ? dinoDuckHeight : dinoHeight;
            const ctx = canvas.getContext('2d');
            
            // 灰色恐龙图像（简单像素风格）
            ctx.fillStyle = '#535353';
            
            if (ducking) {
                // 下蹲的恐龙
                // 身体（更长）
                ctx.fillRect(5, 10, 30, 20);
                
                // 头部（拉长）
                ctx.fillRect(25, 5, 15, 15);
                
                // 腿
                ctx.fillRect(10, 20, 6, 10);
                ctx.fillRect(25, 20, 6, 10);
                
                // 眼睛
                ctx.fillStyle = 'white';
                ctx.fillRect(35, 8, 3, 3);
            } else {
                // 正常站立的恐龙
                // 身体
                ctx.fillRect(15, 10, 20, 28);
                
                // 头部
                ctx.fillRect(24, 0, 20, 20);
                
                // 腿
                ctx.fillRect(15, 38, 6, 10);
                ctx.fillRect(28, 38, 6, 10);
                
                // 手臂
                ctx.fillRect(25, 20, 10, 5);
                
                // 眼睛
                ctx.fillStyle = 'white';
                ctx.fillRect(38, 5, 3, 3);
            }
            
            return canvas.toDataURL();
        }
        
        // 创建仙人掌图像
        function createCactusImage() {
            const canvas = document.createElement('canvas');
            canvas.width = 20;
            canvas.height = 50;
            const ctx = canvas.getContext('2d');
            
            // 深绿色仙人掌
            ctx.fillStyle = '#006400';
            
            // 主干
            ctx.fillRect(7, 0, 6, 50);
            
            // 左枝
            ctx.fillRect(0, 15, 7, 5);
            ctx.fillRect(0, 10, 4, 15);
            
            // 右枝
            ctx.fillRect(13, 25, 7, 5);
            ctx.fillRect(16, 20, 4, 15);
            
            return canvas.toDataURL();
        }
        
        // 创建仙人掌组图像
        function createCactusGroupImage() {
            const canvas = document.createElement('canvas');
            canvas.width = 50;
            canvas.height = 35;
            const ctx = canvas.getContext('2d');
            
            // 深绿色仙人掌组
            ctx.fillStyle = '#006400';
            
            // 左侧仙人掌
            ctx.fillRect(5, 5, 4, 30);
            ctx.fillRect(0, 15, 5, 3);
            ctx.fillRect(9, 10, 5, 3);
            
            // 中间仙人掌
            ctx.fillRect(21, 0, 5, 35);
            ctx.fillRect(16, 10, 5, 3);
            ctx.fillRect(26, 20, 5, 3);
            
            // 右侧仙人掌
            ctx.fillRect(40, 10, 4, 25);
            ctx.fillRect(35, 20, 5, 3);
            ctx.fillRect(44, 15, 5, 3);
            
            return canvas.toDataURL();
        }
        
        // 创建蝙蝠图像
        function createBatImage() {
            const canvas = document.createElement('canvas');
            canvas.width = 40;
            canvas.height = 25;
            const ctx = canvas.getContext('2d');
            
            // 蝙蝠颜色
            ctx.fillStyle = '#444444';
            
            // 蝙蝠身体
            ctx.fillRect(15, 10, 10, 10);
            
            // 翅膀（动画可以在两个状态之间切换）
            // 翅膀状态1 - 展开
            ctx.fillRect(5, 5, 10, 3);
            ctx.fillRect(0, 8, 15, 2);
            ctx.fillRect(25, 5, 10, 3);
            ctx.fillRect(25, 8, 15, 2);
            
            // 眼睛
            ctx.fillStyle = 'white';
            ctx.fillRect(17, 12, 2, 2);
            ctx.fillRect(21, 12, 2, 2);
            
            return canvas.toDataURL();
        }
        
        // 创建死亡恐龙图像
        function createDeadDinoImage() {
            const canvas = document.createElement('canvas');
            canvas.width = dinoWidth;
            canvas.height = isDucking ? dinoDuckHeight : dinoHeight;
            const ctx = canvas.getContext('2d');
            
            // 红色恐龙图像（死亡状态）
            ctx.fillStyle = '#FF0000';
            
            if (isDucking) {
                // 下蹲的恐龙
                // 身体（更长）
                ctx.fillRect(5, 10, 30, 20);
                
                // 头部（拉长）
                ctx.fillRect(25, 5, 15, 15);
                
                // 腿
                ctx.fillRect(10, 20, 6, 10);
                ctx.fillRect(25, 20, 6, 10);
                
                // 眼睛 - X形状表示死亡
                ctx.fillStyle = 'white';
                ctx.fillRect(35, 8, 3, 3);
                ctx.fillStyle = 'black';
                ctx.beginPath();
                ctx.moveTo(34, 7);
                ctx.lineTo(39, 12);
                ctx.moveTo(39, 7);
                ctx.lineTo(34, 12);
                ctx.stroke();
            } else {
                // 正常站立的恐龙
                // 身体
                ctx.fillRect(15, 10, 20, 28);
                
                // 头部
                ctx.fillRect(24, 0, 20, 20);
                
                // 腿
                ctx.fillRect(15, 38, 6, 10);
                ctx.fillRect(28, 38, 6, 10);
                
                // 手臂
                ctx.fillRect(25, 20, 10, 5);
                
                // 眼睛 - X形状表示死亡
                ctx.fillStyle = 'white';
                ctx.fillRect(38, 5, 3, 3);
                ctx.fillStyle = 'black';
                ctx.beginPath();
                ctx.moveTo(37, 4);
                ctx.lineTo(42, 9);
                ctx.moveTo(42, 4);
                ctx.lineTo(37, 9);
                ctx.stroke();
            }
            
            return canvas.toDataURL();
        }
        
        // 键盘按下事件
        document.addEventListener('keydown', function(event) {
            if (event.code === 'Space' || event.code === 'ArrowUp') {
                event.preventDefault();
                jump();
            } else if (event.code === 'ArrowDown') {
                event.preventDefault();
                duck();
            }
        });
        
        // 键盘释放事件
        document.addEventListener('keyup', function(event) {
            if (event.code === 'ArrowDown') {
                event.preventDefault();
                standUp();
            }
        });
        
        // 触摸屏事件
        let touchStartY = 0;
        
        document.addEventListener('touchstart', function(event) {
            event.preventDefault();
            touchStartY = event.touches[0].clientY;
        });
        
        document.addEventListener('touchend', function(event) {
            event.preventDefault();
            const touchEndY = event.changedTouches[0].clientY;
            
            // 向上滑动 - 跳跃
            if (touchEndY < touchStartY - 30) {
                jump();
            }
            // 向下滑动 - 下蹲
            else if (touchEndY > touchStartY + 30) {
                duck();
            }
            // 点击 - 跳跃
            else if (Math.abs(touchEndY - touchStartY) < 10) {
                jump();
            }
            
            // 如果下蹲是通过滑动触发的，需要在滑动结束后恢复站立
            if (isDucking) {
                // 延迟一小段时间后恢复站立姿势
                setTimeout(standUp, 300);
            }
        });
        
        // 监听重启按钮
        document.getElementById('restart-button').addEventListener('click', function() {
            location.reload();
        });
        
        // 开始游戏循环
        requestAnimationFrame(gameLoop);
    </script>
</body>
</html>